from selenium import webdriver
import time
from selenium.webdriver.common.by import By
import pandas as pd


def data_option(data, attribute):
    data_array = []
    for element in data:
        data_array.append(element.get_attribute(attribute))
    re_array = [item for item in data_array if item]
    return re_array


class BrowserMain:
    def __init__(self, search_key):
        self.driver = webdriver.Chrome()
        self.keyword = search_key
        self.BASE_URL = 'https://search.bilibili.com/upuser?keyword=' + search_key + ('&from_source=webtop_search'
                                                                                      '&spm_id_from'
                                                                                      '=333.1007&search_source=5')
        self.page = 1
        self.o = 12
        self.user_desc = []
        self.user_name = []
        self.user_avatar = []

    def init_driver(self):
        self.driver.get(self.BASE_URL)
        self.driver.maximize_window()

    def search(self):
        # 用户简介
        user_desc_ele = self.driver.find_elements(by=By.CLASS_NAME, value='b_text')
        user_desc_data = data_option(user_desc_ele, 'title')
        self.user_desc = self.user_desc + user_desc_data
        # 用户用户名
        user_name_ele = self.driver.find_elements(by=By.CLASS_NAME, value='p_relative')
        user_name_data = data_option(user_name_ele, 'title')
        self.user_name = self.user_name + user_name_data
        # 用户头像
        user_avatar_ele = self.driver.find_elements(by=By.CLASS_NAME, value='bili-avatar-img')
        user_avatar_data = data_option(user_avatar_ele, 'src')
        self.user_avatar = self.user_avatar + user_avatar_data


        # data = {
        #     '用户名': user_name_data,
        #     '简介': user_desc_data,
        #     '头像': user_avatar_data
        # }
        data = {
            '用户名': self.user_name,
            '简介': self.user_desc,
            '头像': self.user_avatar
        }
        print(data)

        # df = pd.DataFrame(data)
        excel_path = './data.xlsx'
        #
        df = pd.DataFrame(pd.DataFrame.from_dict(data, orient='index').values.T, columns=list(data.keys()))
        # # 将DataFrame保存到Excel文件
        df.to_excel(excel_path, index=False, engine='openpyxl')

        with pd.ExcelWriter(excel_path, engine='openpyxl', mode='a', if_sheet_exists='overlay') as writer:
            df1 = pd.DataFrame(pd.read_excel(excel_path, ))
            df_rows = df1.shape[0]  # 获取原数据的行数
            # 将数据df写入excel中的sheet1表,从第一个空行开始写：
            df.to_excel(writer, startrow=df_rows + 1, index=False, header=False)

    def next_page(self):
        self.page += 1
        self.o += 12
        self.search()
        for i in range(100):
            self.driver.execute_script(f'document.documentElement.scrollTop={(i + 1) * 100}')
        page_ele = self.driver.find_elements(by=By.XPATH, value='//*[contains(@class, "vui_pagenation--btn-side")]')
        page_ele[1].click()
        self.BASE_URL = 'https://search.bilibili.com/upuser?keyword=' + self.keyword + ('&from_source=webtop_search'
                                                                                        '&spm_id_from'
                                                                                        f'=333.1007&search_source=5'
                                                                                        f'&page={self.page}&o={self.o}')
        print(self.BASE_URL)
        time.sleep(3)
        self.next_page()

    def begin_class(self):
        self.init_driver()
        time.sleep(1)
        self.next_page()


if __name__ == '__main__':
    # keyword = input('请输入关键字：')
    browser = BrowserMain('火影忍者')
    # browser = BrowserMain(keyword)
    browser.begin_class()
